package com.bw.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.domain.SysRole;
import com.bw.domain.SysRoleMenu;
import com.bw.service.SysRoleMenuService;
import com.bw.service.SysRoleService;
import com.bw.utils.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author bobo棒
 * @date 2024年03月04日 16:18
 */

@RestController
@RequestMapping("role")
public class RoleController {
    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    SysRoleMenuService sysRoleMenuService;
    @Autowired
    RedisTemplate redisTemplate;


    @RequestMapping("list")
    public Result list(){
        List<SysRole> list = sysRoleService.list();
        return Result.success(list);
    }

    /**
     *
     * @param sysRoleMenu
     * @return
     */
    @RequestMapping("bindMenu")
    public Result bindMenu(@RequestBody SysRoleMenu sysRoleMenu){
        //角色编辑防止表单重复提交
        String formKey = DigestUtil.md5Hex(sysRoleMenu.toString());
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(formKey, 1, 2, TimeUnit.MINUTES);
        if(aBoolean){
            boolean b= sysRoleMenuService.edit(sysRoleMenu);
            return b?Result.success():Result.fail();
        }else{
            return Result.fail("请勿重复提交");
        }
    }

    /**
     * 根据角色ID获取菜单ID
     * @return
     */
    @RequestMapping("listMenuIdByRoleId")
    public Result listMenuIdByRoleId(Integer roleId){
      List<Integer> mids=  sysRoleMenuService.listMenuIdByRoleId(roleId);
        return Result.success(mids);
      /*  LambdaQueryWrapper<SysRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysRoleMenu::getRoleId,roleId);
        List<SysRoleMenu> list = sysRoleMenuService.list(wrapper);

        ArrayList<Integer> list1 = new ArrayList<Integer>();
        for (SysRoleMenu sysRoleMenu : list) {
            list1.add(sysRoleMenu.getMenuId());
        }
        return Result.success(list1);*/

    }


    @RequestMapping("del")
    public Result del(Integer id){
     boolean b=   sysRoleService.del(id);
     return b?Result.success():Result.fail();
    }
}
